package com.zhiche.lisa.bms.service.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.zhiche.lisa.bms.controller.bill.BillIoController;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;

/**
 * @Author: WangShuiJin
 * @Description:
 * @Date: Create in 20:26 2018/9/10
 */
@Component
public class UaaUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(BillIoController.class);

    @Value("${security.oauth2.client.clientId}")
    private String getClinetId;
    @Value("${security.oauth2.client.clientSecret}")
    private String getClientSecret;
    @Value("${security.oauth2.client.access-token-uri}")
    private String getTokenUrl;
    @Value("${uaa.socketTimeout}")
    private int socketTimeout;

    public String getTenantToken(String tenantId) {
        Map<String, String> parmers = Maps.newHashMap();
        parmers.put("username", "tech-" + tenantId);
        parmers.put("password", "123456");
        parmers.put("client_id", getClinetId);
        parmers.put("client_secret", getClientSecret);
        parmers.put("grant_type", "password");
        String result = HttpClientUtil.post(getTokenUrl, parmers, socketTimeout);
        if (StringUtils.isEmpty(result)) return null;
        JSONObject jsonObject2 = JSON.parseObject(result);
        if (Objects.nonNull(jsonObject2)) {
            String accessToken = jsonObject2.getString("access_token");
            String authorization = "Bearer " + accessToken;
            return authorization;
        } else {
            return null;
        }
    }
}
